﻿
using JZ_UDI.DataAccess;
using JZ_UDI.DataAccess.DataEntity;
using NLog;
using Spire.Xls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JZ_UDI.Settings
{
    public partial class frmUDI : Form
    {
        public frmUDI()
        {
            InitializeComponent();
        }
        List<Product> lists;
        int addRow=-1;
        frmUdiEdit frmEdit;
        frmUdiAdd frmAdd;
        private void frmUDI_Load(object sender, EventArgs e)
        {
            using (var context=new EFDbContext()) {
                lists =context.Products.ToList().FindAll(o => o.isDeleted == 0); 
                dgv.DataSource = lists;
                gridView1.Columns[0].FieldName= "SerialNumber";
                gridView1.Columns[1].FieldName = "ProductName";
                gridView1.Columns[2].FieldName = "ComponentName";
                gridView1.Columns[3].FieldName = "ProductModel";
                gridView1.Columns[4].FieldName = "ProductSpecification";
                gridView1.Columns[5].FieldName = "MaterialCode";
                gridView1.Columns[6].FieldName = "SterilizationMethod";
                gridView1.Columns[7].FieldName = "ProductCode";
                gridView1.Columns[8].FieldName = "RegistrationNumber";
                gridView1.Columns[9].FieldName = "ProductionLicenseNumber";
                gridView1.Columns[10].FieldName = "PackagingQuantityCode";
                gridView1.Columns[11].FieldName = "VendorCode";
                gridView1.Columns[12].FieldName = "UdiNoCheckCode";
                gridView1.Columns[13].FieldName = "UdiHaveCheckCode";
                gridView1.Columns[14].FieldName = "ProductCategory";
                gridView1.Columns[15].FieldName = "DrainageTubeDiameter";
                gridView1.Columns[16].FieldName = "DrainageTubeLength";
                gridView1.Columns[17].FieldName = "DrainageBallVolume";
                gridView1.Columns[18].FieldName = "DrainageBagVolume";
                gridView1.Columns[19].FieldName = "ProductSpecificationNumber";
                gridView1.Columns[20].FieldName = "SurfaceStates";
                gridView1.Columns[21].FieldName = "Description";
            }
            // 新增行的显示位置
            //gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
            // 奇数行变色 AllowCellMerge 必须为false
            //gridView1.OptionsView.EnableAppearanceOddRow = true;
            //gridView1.Appearance.OddRow.BackColor = Color.AliceBlue;
            // 偶数行变色
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.Appearance.EvenRow.BackColor = Color.FromArgb(248,249,250);
        }

        private void FrmAdd_FormBClosed(object sender, Product result)
        {
            
            lists.Add(result);
            gridView1.FocusedRowHandle = gridView1.RowCount - 1;
            addRow = gridView1.FocusedRowHandle;

            frmAdd.FormBClosed -= FrmAdd_FormBClosed;
            frmAdd.Dispose();
            frmAdd = null;
        }



        private void FrmEdit_FormBClosed(object sender, Product result)
        {
            Product p=lists.Find(o => o.ID == result.ID);
            p.ProductName = result.ProductName;
            p.SerialNumber = result.SerialNumber;
            p.ComponentName = result.ComponentName;
            p.ProductModel = result.ProductModel;
            p.ProductSpecification = result.ProductSpecification;
            p.MaterialCode = result.MaterialCode;
            p.SterilizationMethod = result.SterilizationMethod;
            p.ProductCode = result.ProductCode;
            p.RegistrationNumber = result.RegistrationNumber;
            p.ProductionLicenseNumber = result.ProductionLicenseNumber;
            p.PackagingQuantityCode = result.PackagingQuantityCode;
            p.VendorCode = result.VendorCode;
            p.UdiNoCheckCode = result.UdiNoCheckCode;
            p.UdiHaveCheckCode = result.UdiHaveCheckCode;
            p.ProductCategory = result.ProductCategory;
            p.DrainageTubeDiameter = result.DrainageTubeDiameter;
            p.DrainageTubeLength = result.DrainageTubeLength;
            p.DrainageBallVolume = result.DrainageBallVolume;
            p.DrainageBagVolume = result.DrainageBagVolume;
            p.ProductSpecificationNumber = result.ProductSpecificationNumber;
            p.SurfaceStates = result.SurfaceStates;
            p.Description = result.Description;
            gridView1.RefreshData();

            frmEdit.FormBClosed -= FrmEdit_FormBClosed;
            frmEdit.Dispose();
            frmEdit = null;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmAdd = new frmUdiAdd();
            frmAdd.FormBClosed += FrmAdd_FormBClosed;
            frmAdd.ShowDialog();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            int focusedRowHandle = gridView1.FocusedRowHandle;
            if (focusedRowHandle >= 0) // 确保行句柄是有效的  
            {
                Product product = (Product)gridView1.GetRow(focusedRowHandle); // 获取整行数据（如果是DataRowView或其他绑定对象）  
                frmEdit = new frmUdiEdit();
                frmEdit._Product = product;
                frmEdit.FormBClosed += FrmEdit_FormBClosed;
                frmEdit.ShowDialog();
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            int focusedRowHandle = gridView1.FocusedRowHandle;
            if (focusedRowHandle >= 0) // 确保行句柄是有效的  
            {
                if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                {
                    return;
                }
                Product product = (Product)gridView1.GetRow(focusedRowHandle); // 获取整行数据（如果是DataRowView或其他绑定对象）  
                using (var context = new EFDbContext())
                {
                    Product _p = context.Products.ToList().Find(o => o.ID == product.ID);
                    _p.isDeleted = 1;
                    int count = context.SaveChanges();
                    if (count <= 0)
                    {
                        Global.SaveLogger(LogLevel.Info, Global.logger.Name, "删除失败，ID："+product.ID);
                        MessageBox.Show("删除失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    else
                    {
                        lists.Remove(product);
                    }
                }
                Global.SaveLogger(LogLevel.Info, Global.logger.Name, "删除UDI，ID：" + product.ID);
            }
            frmUDI_Load(null, null);
            gridView1.FocusedRowHandle = focusedRowHandle - 1;
        }

        private void btnOutput_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel档案|*.xlsx";
            sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.FileName = "Product";
            if (sfd.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            Workbook wb = new Workbook();
            wb.Version = ExcelVersion.Version2013;
            Worksheet sheet = wb.Worksheets[0];
            sheet.Name = "Product";
            //输出表头
            for (int i = 0; i <= gridView1.Columns.Count - 1; i++)
            {
                sheet.Range[1, i + 1].Text = gridView1.Columns[i].GetTextCaption();
            }

            int startRow = 2;
            foreach (Product p in lists)
            {
                sheet.Range[startRow, 1].Text = p.SerialNumber.ToString();    //序号
                sheet.Range[startRow, 2].Text = p.ProductName.ToString();//产品名称
                sheet.Range[startRow, 3].Text = string.IsNullOrEmpty(p.ComponentName) ? "" : p.ComponentName.ToString();//组件名称
                sheet.Range[startRow, 4].Text = string.IsNullOrEmpty(p.ComponentName) ? "" : p.ProductModel.ToString();//产品型号
                sheet.Range[startRow, 5].Text = string.IsNullOrEmpty(p.ProductSpecification) ? "" : p.ProductSpecification.ToString();//产品规格
                sheet.Range[startRow, 6].Text = string.IsNullOrEmpty(p.MaterialCode) ? "" : p.MaterialCode.ToString();//材料代号
                sheet.Range[startRow, 7].Text = string.IsNullOrEmpty(p.SterilizationMethod) ? "" : p.SterilizationMethod.ToString();//灭菌方式
                sheet.Range[startRow, 8].Text = string.IsNullOrEmpty(p.ProductCode) ? "" : p.ProductCode.ToString();   //产品编码
                sheet.Range[startRow, 9].Text = string.IsNullOrEmpty(p.RegistrationNumber) ? "" : p.RegistrationNumber.ToString();//注册证编号
                sheet.Range[startRow, 10].Text = string.IsNullOrEmpty(p.ProductionLicenseNumber) ? "" : p.ProductionLicenseNumber.ToString();//生产许可证编号
                sheet.Range[startRow, 11].Text = string.IsNullOrEmpty(p.PackagingQuantityCode) ? "" : p.PackagingQuantityCode.ToString();//包装数量代码
                sheet.Range[startRow, 12].Text = string.IsNullOrEmpty(p.VendorCode) ? "" : p.VendorCode.ToString();//厂商代码
                sheet.Range[startRow, 13].Text = string.IsNullOrEmpty(p.UdiNoCheckCode) ? "" : p.UdiNoCheckCode.ToString();//UDI无校验码
                sheet.Range[startRow, 14].Text = string.IsNullOrEmpty(p.UdiHaveCheckCode) ? "" : p.UdiHaveCheckCode.ToString();//UDI有校验码
                sheet.Range[startRow, 15].Text = string.IsNullOrEmpty(p.ProductCategory) ? "" : p.ProductCategory.ToString();//产品类别
                sheet.Range[startRow, 16].Text = string.IsNullOrEmpty(p.DrainageTubeDiameter) ? "" : p.DrainageTubeDiameter.ToString();//引流管外径
                sheet.Range[startRow, 17].Text = string.IsNullOrEmpty(p.DrainageTubeLength) ? "" : p.DrainageTubeLength.ToString();//引流管长度
                sheet.Range[startRow, 18].Text = string.IsNullOrEmpty(p.DrainageBallVolume) ? "" : p.DrainageBallVolume.ToString();//引流球容积
                sheet.Range[startRow, 19].Text = string.IsNullOrEmpty(p.DrainageBagVolume) ? "" : p.DrainageBagVolume.ToString();//引流袋容积
                sheet.Range[startRow, 20].Text = string.IsNullOrEmpty(p.ProductSpecificationNumber) ? "" : p.ProductSpecificationNumber.ToString();//产品技术要求编号
                sheet.Range[startRow, 21].Text = string.IsNullOrEmpty(p.SurfaceStates) ? "" : p.SurfaceStates.ToString();//表面状态
                startRow++;
            }
            wb.SaveToFile(sfd.FileName, ExcelVersion.Version2013);
            MessageBox.Show("导出Excel完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Global.SaveLogger(LogLevel.Info, Global.logger.Name, "导出UDI数据完成");
        }
    }
}